package com.qr.topics;

import com.rabbitmq.client.BuiltinExchangeType;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;

public class Producer_Topics {

    //发送消息
    public static void main(String[] args) throws Exception{

//        创建连接工厂
        ConnectionFactory connectionFactory = new ConnectionFactory();
//        设置参数
        connectionFactory.setHost("192.168.150.100");
        connectionFactory.setPort(5672);
        //设置虚拟机，有一个默认值/
        connectionFactory.setVirtualHost("/");
        connectionFactory.setUsername("guest");
        connectionFactory.setPassword("guest");

//        创建连接connection
        Connection connection = connectionFactory.newConnection();
//        创建channel
        Channel channel = connection.createChannel();
//        创建交换机
        /**
         * exchange：交换机的名称
         * type:交换机的类型：决定分发的规则
         *      DIRECT:定向
         *      FANOUT：扇形,发送消息到每一个绑定的队列
         *      TOPIC:通配符
         *      HEADERS:参数匹配
         * durable:是否持久化
         * autoDelete：是否自动删除
         * internal:内部使用，一般是false
         * argumens：参数
         */
        String exchangeName = "exchange_topic";
        channel.exchangeDeclare(exchangeName, BuiltinExchangeType.TOPIC,true,false,false,null);

//        创建队列
        String queueName1 = "topic_queue1";
        String queueName2 = "topic_queue2";

        channel.queueDeclare(queueName1,true,false,false,null);
        channel.queueDeclare(queueName2,true,false,false,null);

//        绑定队列和交换机
        /**
         * queue:队列的名称
         * exchange：交换机名称
         * routingKey：绑定的规则
         *
         */

        //队列一的绑定
        channel.queueBind(queueName1,exchangeName,"#.error");
        channel.queueBind(queueName1,exchangeName,"order.*");
        //队列二的绑定
        channel.queueBind(queueName2,exchangeName,"*.*");


//        发送消息
        String body = "exchange_direct";

        //发送消息指定一个routingKey,找我们绑定的队列，走我们绑定的队列
        channel.basicPublish(exchangeName,"order.info",null,body.getBytes());
        channel.basicPublish(exchangeName,"aa.error",null,body.getBytes());

        //释放资源
        channel.close();
        connection.close();

    }

}
